import java.util.Scanner;

public class Main2_1 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        in.nextLine();
        int[][] arr = new int[n][m];
        for (int i = 0; i < n; i++) {
            String[] arr2 = in.nextLine().split(" ");

            for (int j = 1; j < arr2.length; j++) {
                arr[i][Integer.valueOf(arr2[j]) - 1] = 1;
            }
        }
        int check = in.nextInt();
        for (int i = 0; i < check; i++) {
            int a1 = in.nextInt();
            int a2 = in.nextInt();
            int ret = 0;
            for (int j = 0; j < n; j++) {
                if(arr[j][a1 - 1] == 1 && arr[j][a2 - 1] == 1) {
                    ret++;
                }
            }
            System.out.println(ret);
        }
    }
}
